import { Service } from 'egg';

export default class CommentService extends Service {
  /**
   * 添加评论
   */
  async addComment(data: any) {
    const { ctx } = this;
    const userId = ctx.state.user.user_id;

    // 检查美食店是否存在
    const restaurant = await ctx.model.Restaurant.findOne({
      where: { id: data.restaurant_id, status: 'approved' },
    });

    if (!restaurant) {
      ctx.throw(404, '美食店不存在');
    }

    // 创建评论
    const comment = await ctx.model.Comment.create({
      ...data,
      user_id: userId,
    });

    // 更新美食店评分
    // await this.updateRestaurantGrade(data.restaurant_id);

    return comment;
  }

  /**
   * 获取评论列表
   */
  async getCommentList(restaurantId: number, params: any) {
    const { ctx } = this;
    const { page = 1, limit = 10 } = params;
    const offset = (page - 1) * limit;

    const { count, rows } = await ctx.model.Comment.findAndCountAll({
      where: { restaurant_id: restaurantId },
      order: [['created_at', 'DESC']],
      limit: parseInt(limit),
      offset,
      include: [
        { model: ctx.model.User, as: 'user', attributes: ['user_id', 'user_name', 'avatar'] },
      ],
    });

    // 处理图片数据
    const comments = rows.map(comment => {
      const commentData = comment.toJSON() as any;
      if (commentData.pictures) {
        commentData.imgList = commentData?.pictures ? commentData?.pictures.split(',').map((p: string) => ({ url: this.config.host + p, path: p })) : [];
      }
      if (commentData.user?.avatar) {
        commentData.user = {
          ...commentData.user,
          avatar: this.config.host + commentData.user?.avatar,
        }
      }
      return commentData;
    });

    return {
      list: comments,
      total: count,
      page: parseInt(page),
      limit: parseInt(limit),
    };
  }

  /**
   * 删除评论
   */
  async deleteComment(id: number) {
    const { ctx } = this;
    const userId = ctx.state.user.user_id;

    const comment = await ctx.model.Comment.findByPk(id);
    if (!comment) {
      ctx.throw(404, '评论不存在');
    }

    // 检查是否是自己的评论
    if (comment!.user_id !== userId) {
      ctx.throw(403, '只能删除自己的评论');
    }

    // const restaurantId = comment!.restaurant_id;
    await comment!.destroy();

    // 更新美食店评分
    // await this.updateRestaurantGrade(restaurantId);

    return { message: '删除成功' };
  }

  /**
   * 更新美食店评分
   */
  // private async updateRestaurantGrade(restaurantId: number) {
  //   const { ctx } = this;

  //   // 计算平均评分
  //   const result = await ctx.model.Comment.findOne({
  //     where: { restaurant_id: restaurantId },
  //     attributes: [
  //       [ctx.model.fn('AVG', ctx.model.col('grade')), 'avgGrade'],
  //     ],
  //     raw: true,
  //   });

  //   const avgGrade = (result as any)?.avgGrade || 0;

  //   // 更新美食店评分
  //   await ctx.model.Restaurant.update(
  //     { grade: parseFloat(avgGrade.toFixed(2)) },
  //     { where: { id: restaurantId } }
  //   );
  // }
}